package com.jzo2o.orders.manager.strategy.impl;

import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.mapper.OrdersCanceledMapper;
import com.jzo2o.orders.base.mapper.OrdersRefundMapper;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.domain.OrdersCanceled;
import com.jzo2o.orders.base.model.domain.OrdersRefund;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import com.jzo2o.orders.manager.service.impl.OrdersManagerServiceImpl;
import com.jzo2o.orders.manager.strategy.OrderCancelStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

//普通用户派单状态取消订单
@Component("1:DISPATCHING")
public class CommonUserDispatchingOrderCancelStrategy implements OrderCancelStrategy {
    @Autowired
    private OrdersCanceledMapper ordersCanceledMapper;
    @Autowired
    private OrdersRefundMapper ordersRefundMapper;
    @Autowired
    private OrdersManagerServiceImpl ordersManagerService;

    /**
     * 订单取消
     *
     * @param orderCancelDTO 取消订单的参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancel(OrderCancelDTO orderCancelDTO) {
        //修改订单的状态为已关闭，保存取消订单的记录，添加待退款记录
        //700 已关闭
        //将订单状态改为已关闭
        ordersManagerService.lambdaUpdate().set(Orders::getOrdersStatus, OrderStatusEnum.CLOSED.getStatus())
                //订单状态为派单中
                .eq(Orders::getOrdersStatus, OrderStatusEnum.DISPATCHING.getStatus())
                //订单id相等
                .eq(Orders::getId, orderCancelDTO.getId()).update();
        // 2保存取消订单记录
        OrdersCanceled ordersCanceled = new OrdersCanceled();
        //订单id
        ordersCanceled.setId(orderCancelDTO.getId());
        //取消人ID
        ordersCanceled.setCancellerId(orderCancelDTO.getCurrentUserId());
        //取消人名称
        ordersCanceled.setCancelerName(orderCancelDTO.getCurrentUserName());
        //取消人类型，1：普通用户，4：运营人员
        ordersCanceled.setCancellerType(orderCancelDTO.getCurrentUserType());
        //取消原因
        ordersCanceled.setCancelReason(orderCancelDTO.getCancelReason());
        //取消时间
        ordersCanceled.setCancelTime(LocalDateTime.now());
        //订单取消映射器
        ordersCanceledMapper.insert(ordersCanceled);
        //添加待退款记录
        OrdersRefund ordersRefund = new OrdersRefund();
        //订单id
        ordersRefund.setId(orderCancelDTO.getId());
        //支付服务交易单号
        ordersRefund.setTradingOrderNo(orderCancelDTO.getTradingOrderNo());
        //实付金额
        ordersRefund.setRealPayAmount(orderCancelDTO.getRealPayAmount());
        //订单是待支付
        ordersRefund.setCreateTime(LocalDateTime.now());
        ordersRefundMapper.insert(ordersRefund);
    }
}
